package com.example.ai_basedintelligentdiagnosisandtreatmentofchildren.viewmodel;

import android.util.Patterns;

import androidx.lifecycle.LiveData;
import androidx.lifecycle.MutableLiveData;
import androidx.lifecycle.ViewModel;

import com.example.ai_basedintelligentdiagnosisandtreatmentofchildren.R;
import com.example.ai_basedintelligentdiagnosisandtreatmentofchildren.utils.ValidationResult;

import java.util.Random;

/**
 * 忘记密码功能视图模型
 * 职责：处理密码重置业务流程和表单验证逻辑
 */
public class ForgetPasswordViewModel extends ViewModel {
    // region 常量声明
    private static final int CODE_LENGTH = 6;    // 验证码长度
    private static final int COUNTDOWN_SECONDS = 60; // 倒计时总秒数
    private long codeGenerationTime = 0;
    private static final long CODE_VALID_DURATION = 5 * 60 * 1000; // 5分钟有效期（单位：毫秒）
    // endregion

    // region LiveData
    private final MutableLiveData<Integer> _countdown = new MutableLiveData<>(0);
    private final MutableLiveData<String> _verificationCode = new MutableLiveData<>();
    private final MutableLiveData<Boolean> _isLoading = new MutableLiveData<>(false);
    // endregion

    // region 公共暴露的LiveData
    /** 获取倒计时剩余秒数 */
    public LiveData<Integer> getCountdown() { return _countdown; }

    /** 获取生成的验证码（测试用途） */
    public LiveData<String> getVerificationCode() { return _verificationCode; }

    /** 获取加载状态 */
    public LiveData<Boolean> isLoading() { return _isLoading; }
    // endregion

    // region 业务逻辑
    /**
     * 处理发送验证码逻辑
     * @param account 用户输入的手机号或邮箱
     */
    public void handleSendVerificationCode(String account) {
        // 生成随机验证码（模拟服务端生成）
        String generatedCode = generateRandomCode(CODE_LENGTH);
        _verificationCode.setValue(generatedCode);
        codeGenerationTime = System.currentTimeMillis(); // 记录生成时间
        // 启动倒计时
        startCountdownTimer();
    }

    /** 启动倒计时计时器 */
    private void startCountdownTimer() {
        _countdown.setValue(COUNTDOWN_SECONDS);
        new Thread(() -> {
            try {
                for (int i = COUNTDOWN_SECONDS - 1; i >= 0; i--) {
                    Thread.sleep(1000);
                    _countdown.postValue(i);
                }
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
            }
        }).start();
    }
    // endregion

    // region 验证逻辑
    /**
     * 验证账户格式（手机号/邮箱）
     * @param account 用户输入的账户
     * @return 验证结果对象
     */
    public ValidationResult validateAccount(String account) {
        if (account.isEmpty()) {
            return new ValidationResult(false, R.string.error_account_empty);
        }
        if (!isValidPhone(account) && !isValidEmail(account)) {
            return new ValidationResult(false, R.string.error_account_invalid);
        }

        return new ValidationResult(true, 0);
    }

    public ValidationResult validateVerificationCode(String inputCode) {
        // 非空检查
        if (inputCode.isEmpty()) {
            return ValidationResult.invalid(R.string.error_verification_code_empty);
        }

        // 过期检查
        if (System.currentTimeMillis() - codeGenerationTime > CODE_VALID_DURATION) {
            return ValidationResult.invalid(R.string.error_verification_code_expired);
        }

        // 正确性检查
        String realCode = _verificationCode.getValue();
        if (realCode == null || !realCode.equals(inputCode)) {
            return ValidationResult.invalid(R.string.error_verification_code_invalid);
        }

        return ValidationResult.valid();
    }

    public ValidationResult validateConfirmPassword(String confirmPassword) {
        if (confirmPassword.isEmpty()) {
            return new ValidationResult(false, R.string.error_confirm_password_empty);
        }
        return new ValidationResult(true, 0);
    }

    /**
     * 验证密码格式
     * @param password 用户输入的密码
     * @return 验证结果对象
     */
    public ValidationResult validatePassword(String password) {
        if (password.length() < 8) {
            return new ValidationResult(false, R.string.error_password_length);
        }
        if (!password.matches("^(?=.*[A-Za-z])(?=.*\\d).+$")) {
            return new ValidationResult(false, R.string.error_password_format);
        }
        return new ValidationResult(true, 0);
    }
    // endregion

    // region 工具方法
    /** 生成指定位数的数字验证码 */
    private String generateRandomCode(int length) {
        Random random = new Random();
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < length; i++) {
            sb.append(random.nextInt(10));
        }
        return sb.toString();
    }

    /** 验证手机号格式 */
    private boolean isValidPhone(String input) {
        return input.length() == 11 && input.startsWith("1");
    }

    /** 验证邮箱格式 */
    private boolean isValidEmail(String input) {
        return Patterns.EMAIL_ADDRESS.matcher(input).matches();
    }
    // endregion

    // region 密码重置逻辑
    private final MutableLiveData<Boolean> _resetSuccess = new MutableLiveData<>();
    private final MutableLiveData<String> _resetError = new MutableLiveData<>();

    public LiveData<Boolean> getResetSuccess() { return _resetSuccess; }
    public LiveData<String> getResetError() { return _resetError; }

    /**
     * 执行密码重置（模拟实现）
     */
    public void performPasswordReset(String account, String newPassword, String code) {
        new Thread(() -> {
            try {
                // 模拟网络请求延迟
                Thread.sleep(1500);

                // 本地验证最终一致性（虽然前面已经验证过）
                if (!code.equals(_verificationCode.getValue())) {
                    _resetError.postValue("系统验证失败，请重新操作");
                    return;
                }

                // TODO: 实际开发中此处调用API
                _resetSuccess.postValue(true);
            } catch (InterruptedException e) {
                _resetError.postValue("请求超时，请重试");
            }
        }).start();
    }
// endregion
}